package com.zb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.SelectResultVo;
import com.zb.entity.SelectVo;
import com.zb.entity.ZjWorkLevel;
import com.zb.entity.ZjWorkOrder;
import com.zb.mapper.ZjWorkLevelMapper;
import com.zb.result.PageUtil;
import com.zb.service.ZjWorkLevelService;
import com.zb.service.ZjWorkOrderService;
import com.zb.vo.WorkLevelListVo;
import com.zb.vo.WorkLevelVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 工单等级表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-09-12
 */
@Service
public class ZjWorkLevelServiceImpl extends ServiceImpl<ZjWorkLevelMapper, ZjWorkLevel> implements ZjWorkLevelService {
    @Resource
    private ZjWorkLevelMapper workLevelMapper;
    @Resource
    private ZjWorkOrderService workOrderService;

    // 新增或修改工单级别
    @Override
    @Transactional
    public void save(Long custAccId, WorkLevelVo workLevelVo) {
        Assert.isTrue(null == workLevelMapper.existByName(custAccId, workLevelVo.getId(), workLevelVo.getName()), "级别名称已重复");
        ZjWorkLevel level = new ZjWorkLevel();
        BeanUtils.copyProperties(workLevelVo, level);
        level.setDisalbed(workLevelVo.getStatus());

        ZjWorkLevel defaultLevel = workLevelMapper.getDefaultLevelByCustAccId(custAccId);
        if (null != defaultLevel && !workLevelVo.getDefaultLevel() && Objects.equals(defaultLevel.getId(), level.getId())) {
            Assert.isTrue(false, "此级别为默认级别，请重新指定默认后再修改！");
        }

        List<ZjWorkLevel> adds = new ArrayList<>();
        List<ZjWorkLevel> updates = new ArrayList<>();

        if (null != level.getId()) {
            if (level.getDefaultLevel() && null != defaultLevel && !Objects.equals(defaultLevel.getId(), level.getId())) {
                defaultLevel.setDefaultLevel(false);
                updates.add(defaultLevel);
            }
            updates.add(level);
        } else {
            if (level.getDefaultLevel() && null != defaultLevel) {
                defaultLevel.setDefaultLevel(false);
                updates.add(defaultLevel);
            }
            if (null == defaultLevel && !level.getDefaultLevel()) {
                level.setDefaultLevel(true);
            }
            level.setId(IdWorker.getId());
            level.setCustAccId(custAccId);
            level.setColor(null == level.getColor()? "" : level.getColor());
            level.setWeight(null == level.getWeight()? 1 : level.getWeight());
            adds.add(level);
        }
        if (!adds.isEmpty()) this.saveBatch(adds);
        if (!updates.isEmpty()) this.updateBatchById(updates);
    }

    // 获取工单级别列表
    @Override
    public Map<String, Object> getList(Long custAccId, SelectVo selectVo) {
        QueryWrapper<ZjWorkLevel> wrapper = new QueryWrapper<>();
        wrapper.eq("cust_acc_id", custAccId);
        wrapper.orderByDesc("is_default_level", "gmt_update");
        if (StringUtils.isNotBlank(selectVo.getName())) {
            wrapper.like("name", selectVo.getName());
        }
        PageUtil.setPageLimit(selectVo);
        Page<ZjWorkLevel> page = this.page(new Page<>(selectVo.getPage(), selectVo.getLimit()), wrapper);
        List<WorkLevelListVo> voList = page.getRecords().stream().map(level -> {
            WorkLevelListVo vo = new WorkLevelListVo();
            BeanUtils.copyProperties(level, vo);
            vo.setStatus(level.getDisalbed());
            vo.setCreateTime(level.getGmtCreate());
            vo.setUpdateTime(level.getGmtUpdate());
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    // 根据级别ID获取工单级别详情
    @Override
    public WorkLevelVo getDetail(Long id) {
        ZjWorkLevel level = this.getById(id);
        Assert.isTrue(null != level, "级别参数[" + id + "]的数据不存在");
        WorkLevelVo vo = new WorkLevelVo();
        BeanUtils.copyProperties(level, vo);
        vo.setStatus(level.getDisalbed());
        return vo;
    }

    // 根据级别ID批量启用或禁用工单级别
    @Override
    public void updateDisabledBatchById(List<Long> idList, boolean status) {
        workLevelMapper.updateDisabledBatchById(idList, status);
    }

    // 根据级别ID批量删除工单级别
    @Override
    public void deleteBatchById(List<Long> ids) {
        if (null == ids || ids.isEmpty()) {
            return;
        }
        QueryWrapper<ZjWorkOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.select("work_level_id");
        orderQueryWrapper.in("work_level_id", ids);
        orderQueryWrapper.last("limit 10");
        List<ZjWorkOrder> orderList = workOrderService.list(orderQueryWrapper);
        if (CollectionUtil.isNotEmpty(orderList)) {
            QueryWrapper<ZjWorkLevel> wrapper = new QueryWrapper<>();
            wrapper.select("name");
            wrapper.in("id", orderList.stream().map(ZjWorkOrder::getWorkLevelId).distinct().toList());
            List<ZjWorkLevel> levelList = this.list(wrapper);
            Assert.isTrue(false, "级别名称[ "+ levelList.stream().map(ZjWorkLevel::getName).collect(Collectors.joining("、")) +" ]已被工单关联使用，不允许删除");
        }
        this.removeByIds(ids);
    }

    // 工单级别下拉列表查询
    @Override
    public Map<String, Object> workLevelPageSelect(Long custAccId, SelectVo selectVo) {
        QueryWrapper<ZjWorkLevel> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name", "is_default_level AS defaultLevel");
        wrapper.orderByDesc("is_default_level", "gmt_update");
        wrapper.eq("cust_acc_id", custAccId).eq("is_disalbed", false);
        if (StringUtils.isNotBlank(selectVo.getName())) {
            wrapper.like("name", selectVo.getName());
        }
        PageUtil.setSelectPageLimit(selectVo);
        Page<ZjWorkLevel> page = this.page(new Page<>(selectVo.getPage(), selectVo.getLimit()), wrapper);
        List<SelectResultVo> voList = page.getRecords().stream().map(level -> {
            return new SelectResultVo(level.getId(), level.getName(), level.getDefaultLevel());
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    // 根据ID获取工单级别信息
    @Override
    public List<ZjWorkLevel> getByIds(List<Long> ids) {
        if (null ==  ids || ids.isEmpty()) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkLevel> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name", "color", "weight", "is_disalbed AS disalbed", "is_default_level AS defaultLevel");
        wrapper.in("id", ids);
        return this.list(wrapper);
    }

    // 根据商家ID获取默认等级ID
    @Override
    public Long getDefaultLevelIdByCustAccId(Long custAccId) {
        QueryWrapper<ZjWorkLevel> wrapper = new QueryWrapper<>();
        wrapper.select("id");
        wrapper.eq("cust_acc_id", custAccId)
                .eq("is_default_level", true);
        ZjWorkLevel level = this.getOne(wrapper);
        return null == level? 0L : level.getId();
    }
}
